<?php
 if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class User extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
        
        $this->data['controller'] = 'user';         
        $this->load->model('Muser');
    }
    
	public function index()
    {
        if($this->getParamString('user') == 'guest')
        {
            $this->createguest();
        }
        $id_user = $this->session->userdata('id_mem');
        
        if( in_array($id_user, array(null, '', '0'))){
			redirect('dang-nhap');
		}
        
        if(!in_array($id_user, array(null, '', '0')) && $this->session->userdata('role') == 'member'){
            $this->checkUser($id_user);
        }
        $this->data['data'] = $this->Muser->getUser($id_user);
        
		$this->data['action'] = 'index';
        $this->load->view('template/layout', $this->data);
    }
    
    public function changpass()
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('old_password', 'Mật khẩu cũ', 'required');
        $this->form_validation->set_rules('password', 'Mật khẩu mới', 'required|matches[verify_password]');
        
        if($this->form_validation->run() === TRUE)
        {
            $oldp = $this->getParamString('old_password');
            $newp = $this->getParamString('password');
               
            $this->data['changepass'] = $this->Muser->changePassUser($oldp,$newp);
            if($this->data['changepass'] = 200)
            {
                redirect('');
            }   
        }
        $this->data['action'] = 'changepass';
        $this->load->view('template/layout', $this->data);
    }
    
    public function forgotpass()
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('username', 'Tên đăng nhập', 'required');
        if($this->form_validation->run() === TRUE)
        {
			$this->data['success'] = '';
            $username = $this->getParamString('username');
            $tdata = $this->Muser->forgotpassB($username);
            if($tdata == 200)
            {
				header('Location: '.$baseurl.'dang-nhap.html?type=mobile');
            }else{
                //$this->data['success'] = null;
            }
        }
		$this->data['action'] = 'forgotpass';
        $this->load->view('template/layout', $this->data);
    }
	
    public function login()
    {
        if(!in_array($this->session->userdata('id_mem'), array(null, '', '0')) && $this->session->userdata('role') == 'member')
        {
            redirect('tai-khoan');
        }
        @$this->data['type'] = $this->getParamString('type');
        if(in_array($this->data['type'], array(null, '', '0')))
        {
    		$this->data['action'] = 'login';
            $this->load->view('template/layout', $this->data);
        }else if(in_array($this->data['type'], array('mobile', 'mobile.html'))){
            $this->data['username'] = '';
            if(!in_array(@$this->session->userdata('username'), array(null, '', '0')))
            {
                $this->data['username'] = $this->session->userdata('username');
            }
            $this->load->library('form_validation');
            $this->form_validation->set_rules('username', 'Tên đăng nhập', 'required');
            $this->form_validation->set_rules('password', 'Mật khẩu', 'required');
            if($this->form_validation->run() === TRUE)
            {
                $uname = $this->getParamString('username');
                $upass = $this->getParamString('password');
                $this->data['login'] = $this->Muser->loginUser($uname, $upass);
                
                if($this->data['login'] == 200)
                {
                    redirect('tai-khoan');
                }else{
                    $this->data['result'] = 201;
                }
            }
            $this->data['action'] = 'login-mobile';
            $this->load->view('template/layout', $this->data);
        }else if(in_array($this->data['type'], array('google', 'google.html'))){
            
            if(!in_array(@$_GET['error'], array(null, ''. '0')))
            {
                redirect('tai-khoan');   
            }
            $google_client_id 		= '634642250818-fj48dupk38c1toegifelneiass9th5pd.apps.googleusercontent.com';
            $google_client_secret 	= 'W2UEXZ8YpfCRqmxjLYOPDo7n';
            $google_redirect_url 	= 'http://hoakhoiaodai.vtvnow.vn/auth-google.html'; //path to your script
            $google_developer_key 	= 'AIzaSyB_pKSlqQsMSeUnY0ZN5LLUIwTTgBGGWyg'; 
            
            require_once PROJECT_PATH."/lib/google/src/Google_Client.php";
            require_once PROJECT_PATH."/lib/google/src/contrib/Google_Oauth2Service.php";
            
            $gClient = new Google_Client();
            $gClient->setApplicationName('NHATNV');
            $gClient->setClientId($google_client_id);
            $gClient->setClientSecret($google_client_secret);
            $gClient->setRedirectUri($google_redirect_url);
            $gClient->setDeveloperKey($google_developer_key);
            
            $google_oauthV2 = new Google_Oauth2Service($gClient);
            
            if (isset($_REQUEST['reset'])) 
            {
              unset($_SESSION['token']);
              $gClient->revokeToken();
              header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL)); //redirect user back to page
            }
            
            if (isset($_GET['code'])) 
            { 
            	$gClient->authenticate($_GET['code']);
            	$_SESSION['token'] = $gClient->getAccessToken();
            	header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL));
            	return;
            }
            
            if (isset($_SESSION['token'])) 
            { 
            	$gClient->setAccessToken($_SESSION['token']);
            }
            
            
            if ($gClient->getAccessToken()) 
            {
            	  $user 				= $google_oauthV2->userinfo->get();
            	  $user_id 				= $user['id'];
            	  $name 			    = filter_var($user['name'], FILTER_SANITIZE_SPECIAL_CHARS);
            	  $email 				= filter_var($user['email'], FILTER_SANITIZE_EMAIL);
            	  $profile_url 			= filter_var($user['link'], FILTER_VALIDATE_URL);
            	  $profile_image_url 	= filter_var($user['picture'], FILTER_VALIDATE_URL);
            	  $_SESSION['token'] 	= $gClient->getAccessToken();
               
                  $profile_image = $this->saveimg($profile_image_url, 1);    
                  
                  $run = $this->Muser->regGoogleDB($user_id, '00009993', $email, 0, $profile_url, $name, $profile_image);
                  if($run->status == '200')
                    {
                        $login = $this->Muser->loginUser($user_id, '00009993');   
                        if($login == '200')
                        {
                             die('<script>window.location="'.$this->data['baseurl'].'tai-khoan.html";</script>');
                        }    
                    }
            }
            else 
            {            
            	redirect($gClient->createAuthUrl());
            }
            
            $this->data['action'] = 'login-google';
            $this->load->view('template/layout', $this->data);
        }
        
    }
    
    public function loginsdt()
    {
        $this->data['username'] = '';
        if(!in_array(@$this->session->userdata('username'), array(null, '', '0')))
        {
            $this->data['username'] = $this->session->userdata('username');
        }
        $this->load->library('form_validation');
        $this->form_validation->set_rules('username', 'Tên đăng nhập', 'required');
        $this->form_validation->set_rules('password', 'Mật khẩu', 'required');
        if($this->form_validation->run() === TRUE)
        {
            $uname = $this->getParamString('username');
            $upass = $this->getParamString('password');
            $this->data['login'] = $this->Muser->loginUser($uname, $upass);
            if($this->data['login'] = 200)
            {
                redirect('tai-khoan');
            }else{
                $this->data['result'] = 201;
            }
        }
		$this->data['action'] = 'loginsdt';
        $this->load->view('template/layout', $this->data);
    }
	
	
	
    public function register()
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('username', 'Tên đăng nhập', 'required');
        
        if($this->form_validation->run() === TRUE)
        {
            $username = $this->getParamString('username');
            $this->data['login'] = $this->Muser->registerUser($username);
            if($this->data['login'] == 200)
            {
                $this->data['success'] = $username;
            }else{
                $this->data['success'] = null;
            }
        }
		$this->data['action'] = 'register';
        $this->load->view('template/layout', $this->data);
    }
    
    public function logout()
    {
        $data_ = array(
                'id_mem'             => ''
            );
        //$this->session->set_userdata($data_);
        $this->session->sess_destroy();
        
        redirect('dang-nhap');
    }
	
    
	public function changepass()
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('old_password', 'Mật khẩu cũ', 'required');
        $this->form_validation->set_rules('password', 'Mật khẩu mới', 'required|matches[verify_password]');
        
        if($this->form_validation->run() === TRUE)
        {
            $oldp = $this->getParamString('old_password');
            $newp = $this->getParamString('password');
            $newp1 = $this->getParamString('verify_password');
            
            $this->data['changepass'] = $this->Muser->changepassUser($oldp,$newp,$newp1);
            if($this->data['changepass'] = 200)
            {
                redirect('');
            }   
        }
        $this->data['action'] = 'changepass';
        $this->load->view('template/layout', $this->data);
        
    }
    
    
    public function loginfb()
    {
        require_once PROJECT_PATH."/lib/fb/facebook.php"; //include facebook SDK
		$facebook = new Facebook(array('appId'  => '569698559784156','secret' => '75c677dbfcd40add946ee4f190ee79fa',));
        
        $user = $facebook->getUser();
        if ($user) {
          try {
            $user = $facebook->api('/me');
          } catch (FacebookApiException $e) {
            error_log($e);
            $user = null;
          }
        }
        
        if ($user) {
          $logoutUrl = $facebook->getLogoutUrl();
        } else {
          $loginUrl = $facebook->getLoginUrl();
        }
        @$vf = $this->getParamString('error');
        @$code = $this->getParamString('code');
        if(in_array(@$logoutUrl, array(null, '', '0')))
        {
            
            if(!in_array($vf, array(null, '', '0')))
            {
                die('<script>window.location="'.$loginUrl.'";</script>');
            }
            if(!in_array($code, array(null, '', '0')))
            {
                
                $_img_large = json_decode(file_get_contents('https://graph.facebook.com/'.$user['id'].'/picture?type=large&redirect=false'));
                
                $profile_image = $this->saveimg($_img_large->data->url, 1);
                
                $fullname = @$user['name'] ? @$user['name'] : $user['id'];
                $link_fb = @$user['username'] ? @$user['username'] : $user['id'];
                if(in_array(@$user['email'], array(null, '', '0')))
                {
                    $email = '';
                }else{
                    $email = @$user['email'];
                }
                
                $run = $this->Muser->regDB($user['id'], $passwd_new, $email, 1, 'https://www.facebook.com/'.$link_fb, $fullname, $profile_image);
                if($run->status == '200')
                {
                    $login = $this->Muser->loginUser($user['id'], $passwd_new);   
                    if($login == '200')
                    {
                        die(json_encode((object)array('status' => $login)));
                    }    
                }
            }
            $arr = (object)array('status' => '203', 'url' => $loginUrl);   
            die(json_encode($arr));
        }else{
            $passwd_new = 'nhatnv';
            
            
            $_img_large = json_decode(file_get_contents('https://graph.facebook.com/'.$user['id'].'/picture?type=large&redirect=false'));
            
            $profile_image = $this->saveimg($_img_large->data->url, 1);
                
            
            $fullname = @$user['name'] ? @$user['name'] : $user['id'];
            $link_fb = @$user['username'] ? @$user['username'] : $user['id'];
            if(in_array(@$user['email'], array(null, '', '0')))
            {
                $email = '';
            }else{
                $email = @$user['email'];
            }
                
            $run = $this->Muser->regDB($user['id'], $passwd_new, $email, 1, 'https://www.facebook.com/'.$link_fb, $fullname, $profile_image);
            
            if($run->status == '200')
            {
                $login = $this->Muser->loginUser($user['id'], $passwd_new);
                if(!in_array($code, array(null, '', '0')))
                    {
                        
                        die('<script>window.location="'.$this->data['baseurl'].'tai-khoan.html";</script>');
                    }
                if($login == 200)
                {                    
                    die(json_encode((object)array('status' => $login)));
                }    
            }
            die('<script>window.location="'.$this->data['baseurl'].'tai-khoan.html";</script>');
        }
    }    
    
    private function saveimg($img, $type)
    {
        $link_img = 'images/avarta/'.$type.'-'.date('Ymdhisis').'-12.jpg';
        @mkdir(PROJECT_PATH.'/data/images/avarta/', 0301, true);
        $t1 = copy(trim($img), PROJECT_PATH.'/data/'.$link_img);
        return $link_img;
    }

    
    public function google()
    {
        if(!in_array(@$_GET['error'], array(null, ''. '0')))
        {
            redirect('tai-khoan');   
        }
            $google_client_id 		= '634642250818-fj48dupk38c1toegifelneiass9th5pd.apps.googleusercontent.com';
            $google_client_secret 	= 'W2UEXZ8YpfCRqmxjLYOPDo7n';
            $google_redirect_url 	= 'http://hoakhoiaodai.vtvnow.vn/auth-google.html'; //path to your script
            $google_developer_key 	= 'AIzaSyB_pKSlqQsMSeUnY0ZN5LLUIwTTgBGGWyg';    
            
        require_once PROJECT_PATH."/lib/google/src/Google_Client.php";
        require_once PROJECT_PATH."/lib/google/src/contrib/Google_Oauth2Service.php";
        
        $gClient = new Google_Client();
        $gClient->setApplicationName('NHATNV');
        $gClient->setClientId($google_client_id);
        $gClient->setClientSecret($google_client_secret);
        $gClient->setRedirectUri($google_redirect_url);
        $gClient->setDeveloperKey($google_developer_key);
        
        $google_oauthV2 = new Google_Oauth2Service($gClient);
        
        if (isset($_REQUEST['reset'])) 
        {
          unset($_SESSION['token']);
          $gClient->revokeToken();
          header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL)); //redirect user back to page
        }
        
        if (isset($_GET['code'])) 
        { 
        	$gClient->authenticate($_GET['code']);
        	$_SESSION['token'] = $gClient->getAccessToken();
        	header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL));
        	return;
        }
        
        if (isset($_SESSION['token'])) 
        { 
        	$gClient->setAccessToken($_SESSION['token']);
        }
        
        
        if ($gClient->getAccessToken()) 
        {
        	  $user 				= $google_oauthV2->userinfo->get();
        	  $user_id 				= $user['id'];
        	  $name 			    = filter_var($user['name'], FILTER_SANITIZE_SPECIAL_CHARS);
        	  $email 				= filter_var($user['email'], FILTER_SANITIZE_EMAIL);
        	  $profile_url 			= filter_var($user['link'], FILTER_VALIDATE_URL);
        	  $profile_image_url 	= filter_var($user['picture'], FILTER_VALIDATE_URL);
        	  $_SESSION['token'] 	= $gClient->getAccessToken();
           
              $profile_image = $this->saveimg($profile_image_url, 1);    
              
              $run = $this->Muser->regGoogleDB($user_id, '00009993', $email, 0, $profile_url, $name, $profile_image);
              if($run->status == '200')
                {
                    $login = $this->Muser->loginUser($user_id, '00009993');   
                    if($login == '200')
                    {
                         die('<script>window.location="'.$this->data['baseurl'].'tai-khoan.html";</script>');
                    }    
                }
        }
        else 
        {            
        	die($gClient->createAuthUrl());
        }
    }      
	
	public function ajaxupdateinfo(){
		$this->data['data'] = $this->Muser->ajaxupdateinfo();
		$this->load->view('template/user/ajaxupdateinfo', $this->data);
	}
        
}
